﻿namespace aspx2razorForms
{
    using System;
    using System.ComponentModel.Composition;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;
    using Telerik.RazorConverter;
    using Telerik.RazorConverter.Razor.DOM;
    using System.ComponentModel.Composition.Hosting;
    using System.Collections.Generic;

    public partial class Form1 : Form
    {
        [Import]
        private IWebFormsParser Parser
        {
            get;
            set;
        }

        [Import]
        private IWebFormsConverter<IRazorNode> Converter
        {
            get;
            set;
        }

        [Import]
        private IRenderer<IRazorNode> Renderer
        {
            get;
            set;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Form1"/> class.
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            lblStatus.Text = string.Empty;
            var catalog = new AssemblyCatalog(typeof(IWebFormsParser).Assembly);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }


        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenWebFormFileDialog = new OpenFileDialog();


            if (checkedListBox1.Items != null && checkedListBox1.Items.Count > 0)
            {
                string lastPath = checkedListBox1.Items[checkedListBox1.Items.Count - 1].ToString();
                OpenWebFormFileDialog.InitialDirectory = lastPath;
            }
            else
            {
                OpenWebFormFileDialog.InitialDirectory = Directory.GetCurrentDirectory(); 
            }

            OpenWebFormFileDialog.Filter = "ASPX files (*.aspx)|*.aspx|ASCX fIles (*.ascx)|*.ascx";
            OpenWebFormFileDialog.FilterIndex = 1;
            OpenWebFormFileDialog.RestoreDirectory = true;
            OpenWebFormFileDialog.Multiselect = true;

            if (OpenWebFormFileDialog.ShowDialog() == DialogResult.OK)
            {
                fileErrorProvider.Clear();                

                try
                {
                    
                    foreach (String file in OpenWebFormFileDialog.FileNames) 
                    {
                        if (!checkedListBox1.Items.Contains(file))
                        {
                            checkedListBox1.Items.Add(file);                            
                        }
                    }

                    if (checkedListBox1.Items.Count > 0)
                    {
                        for (int i = 0; i < checkedListBox1.Items.Count; i++)
                        {
                            checkedListBox1.SetItemChecked(i, true);
                        } 
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }

        }


        private void btnBrowseDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            folderBrowserDialog1.Description = "Razor File save location";

            if (checkedListBox1.CheckedItems.Count > 0)
            {
                string firstItem = checkedListBox1.CheckedItems.IndexOf(0).ToString();
                FileInfo info = new FileInfo(firstItem);
                folderBrowserDialog1.SelectedPath = info.DirectoryName;                 
            }

            
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                dirErrorProvider.Clear();
                    
                if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                {
                    txtDir.Text = folderBrowserDialog1.SelectedPath;
                    
                }
            }
        }


        private void btnGenerateRazor_Click(object sender, EventArgs e)
        {
            if (checkedListBox1.CheckedItems.Count <= 0)
            {
                fileErrorProvider.SetError(btnBrowse, "No files to convert.");
                return;
            }


            string directoryName = txtDir.Text;

            if (string.IsNullOrEmpty(directoryName))
            {
                dirErrorProvider.SetError(btnBrowseDir, "Please specify a directory name.");
                return;
            }
            else 
            {
                if (!Directory.Exists(directoryName))
                {
                    dirErrorProvider.SetError(btnBrowseDir, "Invalid directory name.");
                    return;
                }

            }

            try
            {
                GenerateRazorFiles(ConvertAndStoreRazorFiles, directoryName, checkedListBox1);
                
            }
            catch (Exception exc)
            {
                throw new Exception("Unable to convert Web Forms files", exc.InnerException);
 
            }            
            

            lblStatus.Text = "Converted!";
            System.Diagnostics.Process.Start(directoryName);            
        }


        private static void GenerateRazorFiles(Action<string, string, string, string> delegateConvertAndStoreRazorFiles, string directoryName, CheckedListBox checkedListBox1)
        {
            string fileToConvert = string.Empty;
            string inputDirectory = string.Empty;
            string inputFilter = string.Empty;            
            
            foreach (var item in checkedListBox1.CheckedItems)
            {
                fileToConvert = item.ToString();
                inputDirectory = Path.GetDirectoryName(fileToConvert);
                inputFilter = Path.GetFileName(fileToConvert);

                delegateConvertAndStoreRazorFiles(fileToConvert, directoryName, inputDirectory, inputFilter); 
            }

        }


        private void ConvertAndStoreRazorFiles(string fileToConvert, string outputDirectory, string inputDirectory, string inputFilter)
        {
            foreach (var file in Directory.GetFiles(inputDirectory, inputFilter))
            {
                var webFormsPageSource = File.ReadAllText(file, Encoding.UTF8);
                var webFormsDocument = Parser.Parse(webFormsPageSource);
                var razorDom = Converter.Convert(webFormsDocument);
                var razorPage = Renderer.Render(razorDom);

                var outputFile = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(file) + ".cshtml");
                File.WriteAllText(outputFile, razorPage, Encoding.UTF8);
            }
 
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            checkedListBox1.Items.Clear();
            txtDir.Text = string.Empty;
        }

    }
}
